package org.dromara.pc.controller;

import com.fasterxml.jackson.databind.JsonNode;
import com.fasterxml.jackson.databind.ObjectMapper;
import com.fasterxml.jackson.databind.node.ObjectNode;
import jakarta.servlet.http.HttpServletRequest;
import lombok.extern.slf4j.Slf4j;
import org.dromara.cms.domain.bo.CmsArticleBo;
import org.dromara.cms.domain.bo.CmsCategoryBo;
import org.dromara.cms.domain.vo.CmsArticleVo;
import org.dromara.cms.domain.vo.CmsCategoryVo;
import org.dromara.cms.service.ICmsArticleService;
import org.dromara.cms.service.ICmsCategoryService;
import org.dromara.pc.config.FreemarkerConfig;
import org.dromara.system.domain.vo.SysOssVo;
import org.dromara.system.service.ISysOssService;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.core.io.ClassPathResource;
import org.springframework.core.io.Resource;
import org.springframework.http.MediaType;
import org.springframework.http.ResponseEntity;
import org.springframework.stereotype.Controller;
import org.springframework.ui.Model;
import org.springframework.web.bind.annotation.GetMapping;
import org.springframework.web.bind.annotation.PathVariable;
import org.springframework.web.bind.annotation.ResponseBody;

import java.util.ArrayList;
import java.util.HashMap;
import java.util.List;
import java.util.Map;
import java.util.stream.Collectors;


@Slf4j
@Controller
public class IndexController {

    @Autowired
    private FreemarkerConfig freemarkerConfig;
    @Autowired
    private ICmsCategoryService categoryService;
    @Autowired
    private ICmsArticleService articleService;
    @Autowired
    private ISysOssService ossService;

    @GetMapping(value = "/robots.txt", produces = "text/plain")
    @ResponseBody
    public ResponseEntity<Resource> robots() {
        log.info("请求 robots.txt");
        Resource resource = new ClassPathResource("static/robots.txt");
        return ResponseEntity.ok()
            .contentType(MediaType.TEXT_PLAIN)
            .body(resource);
    }
    /**
     * 处理首页
     */
    @GetMapping("/")
    public String index(Model model) {
        try {
            addCommonData(model);
            ObjectMapper mapper = new ObjectMapper();

     

            // 查询 Featured Products (isTop = 3)
            CmsArticleBo featuredBo = new CmsArticleBo();
            featuredBo.setIsTop(3L);
            List<CmsArticleVo> featuredProducts = articleService.queryList(featuredBo);

            // 处理产品数据
            List<Map<String, Object>> processedFeatured = new ArrayList<>();

            for (CmsArticleVo product : featuredProducts) {
                Map<String, Object> productMap = new HashMap<>();
                productMap.put("id", product.getId());
                productMap.put("slug", product.getSlug());

                if (product.getCustomFields() != null) {
                    try {
                        JsonNode customFields = mapper.readTree(product.getCustomFields());
                        if (customFields.has("title")) {
                            productMap.put("title", customFields.get("title").asText());
                        }
                        // 处理缩略图
                        if (customFields.has("thumbs")) {
                            String thumbs = customFields.get("thumbs").asText();
                            String[] thumbIds = thumbs.split(",");
                            if (thumbIds.length > 0) {
                                SysOssVo ossFile = ossService.getById(Long.parseLong(thumbIds[0]));
                                if (ossFile != null) {
                                    productMap.put("thumb", ossFile.getUrl());
                                }
                            }
                        }
                    } catch (Exception e) {
                        log.error("解析产品JSON失败: {}", e.getMessage());
                    }
                }
                processedFeatured.add(productMap);
            }

            model.addAttribute("featuredProducts", processedFeatured);

            // 查询推荐产品
            CmsArticleBo articleBo = new CmsArticleBo();
            articleBo.setIsTop(2L);
            List<CmsArticleVo> recommendProducts = articleService.queryList(articleBo);

            // 处理产品数据
            List<Map<String, Object>> processedProducts = new ArrayList<>();

            for (CmsArticleVo product : recommendProducts) {
                if (processedProducts.size() >= 8) break;  // 只取前8条

                Map<String, Object> productMap = new HashMap<>();
                productMap.put("id", product.getId());
                productMap.put("slug", product.getSlug());

                if (product.getCustomFields() != null) {
                    try {
                        JsonNode customFields = mapper.readTree(product.getCustomFields());
                        if (customFields.has("title")) {
                            productMap.put("title", customFields.get("title").asText());
                        }
                        // 处理缩略图
                        if (customFields.has("thumbs")) {
                            String thumbs = customFields.get("thumbs").asText();
                            String[] thumbIds = thumbs.split(",");
                            if (thumbIds.length > 0) {
                                SysOssVo ossFile = ossService.getById(Long.parseLong(thumbIds[0]));
                                if (ossFile != null) {
                                    productMap.put("thumb", ossFile.getUrl());
                                }
                            }
                        }
                    } catch (Exception e) {
                        log.error("解析产品JSON失败: {}", e.getMessage());
                    }
                }
                processedProducts.add(productMap);
            }

            model.addAttribute("recommendProducts", processedProducts);

            // 查询 application 案例 (isTop = 3)
            CmsArticleBo caseBo = new CmsArticleBo();
            caseBo.setIsTop(3L);
            List<CmsArticleVo> caseList = articleService.queryList(caseBo);

            // 处理案例数据
            List<Map<String, Object>> processedCases = new ArrayList<>();

            for (CmsArticleVo caseItem : caseList) {
                if (processedCases.size() >= 3) break;  // 只取前3条

                Map<String, Object> caseMap = new HashMap<>();
                caseMap.put("id", caseItem.getId());
                caseMap.put("slug", caseItem.getSlug());

                if (caseItem.getCustomFields() != null) {
                    try {
                        JsonNode customFields = mapper.readTree(caseItem.getCustomFields());
                        if (customFields.has("title")) {
                            caseMap.put("title", customFields.get("title").asText());
                        }
                        if (customFields.has("desc")) {
                            caseMap.put("desc", customFields.get("desc").asText());
                        }
                        // 处理缩略图
                        if (customFields.has("thumbs")) {
                            String thumbs = customFields.get("thumbs").asText();
                            String[] thumbIds = thumbs.split(",");
                            if (thumbIds.length > 0) {
                                SysOssVo ossFile = ossService.getById(Long.parseLong(thumbIds[0]));
                                if (ossFile != null) {
                                    caseMap.put("thumb", ossFile.getUrl());
                                }
                            }
                        }
                    } catch (Exception e) {
                        log.error("解析案例JSON失败: {}", e.getMessage());
                    }
                }
                processedCases.add(caseMap);
            }

            model.addAttribute("applicationCases", processedCases);

            return "index";
        } catch (Exception e) {
            log.error("处理首页请求失败: {}", e.getMessage());
            return "error/404";
        }
    }

    /**
     * 处理新闻相关的所有请求
     */
    @GetMapping({"/news", "/news/{category}", "/news/{category}/{slug}"})
    public String handleNews(
        @PathVariable(required = false) String category,
        @PathVariable(required = false) String slug,
        Model model) {
        try {
            addCommonData(model);

            if (slug != null) {
                // 新闻详情页
                model.addAttribute("viewType", "detail");
                model.addAttribute("currentCategory", category);
                model.addAttribute("currentSlug", slug);
            } else if (category != null) {
                // 新闻分类页
                model.addAttribute("viewType", "category");
                model.addAttribute("currentCategory", category);
            } else {
                // 新闻列表页
                model.addAttribute("viewType", "list");
            }

            return "news";
        } catch (Exception e) {
            log.error("处理新闻请求失败: {}", e.getMessage());
            return "error/404";
        }
    }

    /**
     * 处理产品相关的所有请求
     */
    @GetMapping({"/products", "/products/{category}", "/products/{category}/{productSlug}"})
    public String handleProducts(
        @PathVariable(required = false) String category,
        @PathVariable(required = false) String productSlug,
        Model model) {
        try {
            addCommonData(model);

            // 1. 先获取 products 父分类
            CmsCategoryBo parentBo = new CmsCategoryBo();
            parentBo.setTemplate("products.html");
            List<CmsCategoryVo> parentCategories = categoryService.queryList(parentBo);

            Long parentId = null;
            if (!parentCategories.isEmpty()) {
                parentId = parentCategories.get(0).getId();

                if (category != null && productSlug != null) {
                    // 处理产品详情页
                    CmsCategoryBo categoryBo = new CmsCategoryBo();
                    categoryBo.setPath(category);
                    List<CmsCategoryVo> categories = categoryService.queryList(categoryBo);

                    if (!categories.isEmpty()) {
                        CmsCategoryVo currentCategory = categories.get(0);

                        // 获取产品详情
                        CmsArticleBo articleBo = new CmsArticleBo();
                        articleBo.setSlug(productSlug);
                        articleBo.setCategoryId(currentCategory.getId());
                        List<CmsArticleVo> articles = articleService.queryList(articleBo);

                        if (!articles.isEmpty()) {
                            CmsArticleVo article = articles.get(0);
                            Map<String, Object> productMap = new HashMap<>();
                            productMap.put("id", article.getId());
                            productMap.put("slug", article.getSlug());

                            if (article.getCustomFields() != null) {
                                try {
                                    ObjectMapper mapper = new ObjectMapper();
                                    JsonNode customFields = mapper.readTree(article.getCustomFields());
                                    if (customFields.has("title")) {
                                        productMap.put("title", customFields.get("title").asText());
                                    }
                                    if (customFields.has("content")) {
                                        productMap.put("content", customFields.get("content").asText());
                                    }
                                    if (customFields.has("desc")) {
                                        productMap.put("desc", customFields.get("desc").asText());
                                    }

                                    // 处理缩略图
                                    if (customFields.has("thumbs")) {
                                        String thumbs = customFields.get("thumbs").asText();
                                        String[] thumbIds = thumbs.split(",");
                                        if (thumbIds.length > 0) {
                                            try {
                                                Long ossId = Long.parseLong(thumbIds[0]);
                                                SysOssVo byId = ossService.getById(ossId);
                                                if (byId != null) {
                                                    productMap.put("coverImage", byId.getUrl());
                                                }
                                            } catch (NumberFormatException e) {
                                                log.error("转换缩略图ID失败: {}", thumbIds[0]);
                                            }
                                        }
                                    }
                                } catch (Exception e) {
                                    log.error("解析产品JSON失败: {}", e.getMessage());
                                }
                            }

                            model.addAttribute("currentCategory", currentCategory);
                            model.addAttribute("product", productMap);
                            model.addAttribute("viewType", "detail");
                        }
                    }
                } else if (category != null) {
                    // 处理分类页面
        CmsCategoryBo queryBo = new CmsCategoryBo();
                    queryBo.setPath(category);
        List<CmsCategoryVo> categories = categoryService.queryList(queryBo);

                    if (!categories.isEmpty()) {
                        CmsCategoryVo currentCategory = categories.get(0);

                        // 获取该分类下的产品
                        CmsArticleBo articleBo = new CmsArticleBo();
                        articleBo.setCategoryId(currentCategory.getId());
                        List<CmsArticleVo> products = articleService.queryList(articleBo);

                        // 处理每个产品的数据
                        List<Map<String, Object>> processedProducts = new ArrayList<>();
                        ObjectMapper mapper = new ObjectMapper();

                        for (CmsArticleVo product : products) {
                            Map<String, Object> productMap = new HashMap<>();
                            productMap.put("id", product.getId());

                            if (product.getCustomFields() != null) {
                                try {
                                    JsonNode customFields = mapper.readTree(product.getCustomFields());
                                    productMap.put("title", customFields.get("title").asText());
                                    productMap.put("slug", product.getSlug());
                                    productMap.put("desc", customFields.get("pdesc").asText());
                                    // 处理缩略图
                                    if (customFields.has("thumbs")) {
                                        String thumbs = customFields.get("thumbs").asText();
                                        String[] thumbIds = thumbs.split(",");
                                        if (thumbIds.length > 0) {
                                            try {
                                                Long ossId = Long.parseLong(thumbIds[0]);
                                                SysOssVo byId = ossService.getById(ossId);
                                                if (byId != null) {
                                                    productMap.put("coverImage", byId.getUrl());
                                                }
                                            } catch (NumberFormatException e) {
                                                log.error("转换缩略图ID失败: {}", thumbIds[0]);
                                            }
                                        }
                                    }
                                } catch (Exception e) {
                                    log.error("解析产品JSON失败: {}", e.getMessage());
                                }
                            }
                            processedProducts.add(productMap);
                        }

                        model.addAttribute("currentCategory", currentCategory);
                        model.addAttribute("products", processedProducts);
                        model.addAttribute("viewType", "category");
                    }
                } else {
                    // 处理产品列表页
                    CmsCategoryBo categoryBo = new CmsCategoryBo();
                    categoryBo.setParentId(parentId);
                    List<CmsCategoryVo> productCategories = categoryService.queryList(categoryBo);

                    List<Map<String, Object>> categoriesWithProducts = new ArrayList<>();
                    ObjectMapper mapper = new ObjectMapper();

                    for (CmsCategoryVo cat : productCategories) {
                        Map<String, Object> categoryMap = new HashMap<>();
                        categoryMap.put("category", cat);

                        CmsArticleBo articleBo = new CmsArticleBo();
                        articleBo.setCategoryId(cat.getId());
                        List<CmsArticleVo> products = articleService.queryList(articleBo);

                        List<Map<String, Object>> processedProducts = new ArrayList<>();
                        for (CmsArticleVo product : products) {
                            Map<String, Object> productMap = new HashMap<>();
                            productMap.put("id", product.getId());
                            productMap.put("slug", product.getSlug());

                            if (product.getCustomFields() != null) {
                                try {
                                    JsonNode customFields = mapper.readTree(product.getCustomFields());
                                    if (customFields.has("title")) {
                                        productMap.put("title", customFields.get("title").asText());
                                    }

                                    // 处理缩略图
                                    if (customFields.has("thumbs")) {
                                        String thumbs = customFields.get("thumbs").asText();
                                        String[] thumbIds = thumbs.split(",");
                                        if (thumbIds.length > 0) {
                                            try {
                                                Long ossId = Long.parseLong(thumbIds[0]);
                                                SysOssVo byId = ossService.getById(ossId);
                                                if (byId != null) {
                                                    productMap.put("coverImage", byId.getUrl());
                                                }
                                            } catch (NumberFormatException e) {
                                                log.error("转换缩略图ID失败: {}", thumbIds[0]);
                                            }
                                        }
                                    }
                                } catch (Exception e) {
                                    log.error("解析产品JSON失败: {}", e.getMessage());
                                }
                            }
                            processedProducts.add(productMap);
                        }
                        categoryMap.put("products", processedProducts);
                        categoriesWithProducts.add(categoryMap);
                    }

                    model.addAttribute("categoriesWithProducts", categoriesWithProducts);
                }

                // 获取导航用的产品分类
                if (parentId != null) {
                    CmsCategoryBo navBo = new CmsCategoryBo();
                    navBo.setParentId(parentId);
                    List<CmsCategoryVo> navProducts = categoryService.queryList(navBo);
                    model.addAttribute("nav_products", navProducts);
                }
            }

            return "products";
        } catch (Exception e) {
            log.error("处理产品请求失败: {}", e.getMessage());
            return "error/404";
        }
    }

    /**
     * 处理应用相关的所有请求
     */
    @GetMapping({"/application", "/application/{category}", "/application/{category}/{slug}"})
    public String handleApplication(
        @PathVariable(required = false) String category,
        @PathVariable(required = false) String slug,
        Model model) {
        try {
            addCommonData(model);
            log.info("接收到的分类参数: category={}", category);  // 添加日志

            // 查找 application 父分类
            CmsCategoryBo parentBo = new CmsCategoryBo();
            parentBo.setPath("application");
            List<CmsCategoryVo> parentCategories = categoryService.queryList(parentBo);

            if (!parentCategories.isEmpty()) {
                CmsCategoryVo parentCategory = parentCategories.get(0);
                log.info("找到父分类: id={}, path={}", parentCategory.getId(), parentCategory.getPath());  // 添加日志

                // 查询子分类
                CmsCategoryBo subCategoryBo = new CmsCategoryBo();
                subCategoryBo.setParentId(parentCategory.getId());
                List<CmsCategoryVo> subCategories = categoryService.queryList(subCategoryBo);
                log.info("子分类数量: {}", subCategories.size());  // 添加日志
                model.addAttribute("applicationCategories", subCategories);

                // 如果没有指定分类，使用第一个子分类的路径
                if (category == null && !subCategories.isEmpty()) {
                    category = subCategories.get(0).getPath();
                    log.info("使用第一个子分类路径: {}", category);  // 添加日志
                }

                if (category != null) {
                    // 处理分类页
                    CmsCategoryBo categoryBo = new CmsCategoryBo();
                    categoryBo.setPath(category);
                    List<CmsCategoryVo> categories = categoryService.queryList(categoryBo);

                    if (!categories.isEmpty()) {
                        CmsCategoryVo currentCategory = categories.get(0);
                        log.info("当前分类: id={}, path={}", currentCategory.getId(), currentCategory.getPath());  // 添加日志

                        CmsArticleBo articleBo = new CmsArticleBo();
                        articleBo.setCategoryId(currentCategory.getId());
                        List<CmsArticleVo> articles = articleService.queryList(articleBo);

                        // 处理文章中的图片
                        for (CmsArticleVo article : articles) {
                            if (article.getCustomFields() != null) {
                                try {
                                    ObjectMapper mapper = new ObjectMapper();
                                    JsonNode fields = mapper.readTree(article.getCustomFields());
                                    if (fields.has("thumb")) {
                                        String thumbId = fields.get("thumb").asText();
                                        // 获取 OSS 图片 URL
                                        SysOssVo ossFile = ossService.getById(Long.parseLong(thumbId));
                                        if (ossFile != null) {
                                            // 更新 customFields 中的 thumb 字段为实际 URL
                                            ((ObjectNode) fields).put("thumb", ossFile.getUrl());
                                            article.setCustomFields(fields.toString());
                                        }
                                    }
                                } catch (Exception e) {
                                    log.error("处理文章图片失败: {}", e.getMessage());
                                }
                            }
                        }

                        model.addAttribute("articles", articles);
                        model.addAttribute("currentCategory", currentCategory);
                        model.addAttribute("categoryPath", currentCategory.getPath());  // 使用分类对象的 path

                        log.info("设置的分类路径: categoryPath={}", currentCategory.getPath());  // 添加日志
                    }
                }
                if (slug != null) {
                    CmsArticleBo bo = new CmsArticleBo();
                    bo.setSlug(slug);
                    List<CmsArticleVo> cmsArticleVos = articleService.queryList(bo);
                    model.addAttribute("article", cmsArticleVos.get(0));
                    model.addAttribute("slug", slug);
                }
            }

            // 打印所有 model 属性
            log.info("Model attributes:");
            model.asMap().forEach((key, value) -> {
                log.info("Key: {}, Value: {}", key, value);
            });

            return "case";
        } catch (Exception e) {
            log.error("处理应用请求失败: {}", e.getMessage());
            return "error/404";
        }
    }

    /**
     * 处理其他静态页面，包括二级页面
     */
    @GetMapping({"/{page}", "/{parent}/{page}"})
    public String handleStaticPage(
        @PathVariable String page,
        @PathVariable(required = false) String parent, HttpServletRequest request,
        Model model) {
        try {
            addCommonData(model);

            // 查找当前页面对应的分类
            CmsCategoryBo categoryBo = new CmsCategoryBo();
            categoryBo.setPath(page);
            // 添加日志，查看查询条件
            log.info("查询分类条件: path={}", page);

            List<CmsCategoryVo> categories = categoryService.queryList(categoryBo);
            log.info("查找路径: {}, 找到分类数量: {}", page, categories.size());

            if (!categories.isEmpty()) {
                CmsCategoryVo currentCategory = categories.get(0);

                // 打印当前分类的详细信息
                log.info("当前分类详细信息: {}", currentCategory);

                // 直接使用 CmsCategoryVo 对象，不转换为 Map
                model.addAttribute("currentCategory", currentCategory);


                // 处理一级页面
                CmsArticleBo currentArticleBo = new CmsArticleBo();
                currentArticleBo.setCategoryId(currentCategory.getId());
                List<CmsArticleVo> currentArticles = articleService.queryList(currentArticleBo);

                log.info("一级页面文章查询: 分类ID={}, 查询到文章数量={}",
                    currentCategory.getId(), currentArticles.size());

                // 打印每篇文章的信息
                for (CmsArticleVo article : currentArticles) {
                    log.info("文章信息: id={}, customFields={}",
                        article.getId(), article.getCustomFields());
                }
                request.setAttribute("articles", currentArticles);

            }

            // 打印模型中的所有属性
            log.info("Model attributes:");
            model.asMap().forEach((key, value) -> {
                log.info("Key: {}, Value type: {}", key,
                    value != null ? value.getClass().getName() : "null");
            });

            String templateToUse = parent != null ? parent : page;
            log.info("使用模板: {}", templateToUse);
            return templateToUse;

        } catch (Exception e) {
            log.error("处理页面请求失败: ", e);
            return "error/404";
        }
    }

    /**
     * 添加公共数据
     */
    private void addCommonData(Model model) {
        try {
            // 获取菜单数据
            CmsCategoryBo queryBo = new CmsCategoryBo();
            List<CmsCategoryVo> categories = categoryService.queryList(queryBo);

            // 转换为 Map 对象列表，确保包含所有必要字段
            List<Map<String, Object>> categoryList = categories.stream()
                .map(category -> {
                    Map<String, Object> item = new HashMap<>();
                    item.put("id", category.getId());
                    item.put("parentId", category.getParentId() != null ? category.getParentId() : 0L);
                    item.put("title", category.getTitle());
                    item.put("path", category.getPath());
                    item.put("template", category.getTemplate());
                    item.put("isShow", category.getIsShow());  // 确保包含 isShow 字段
                    return item;
                })
                .collect(Collectors.toList());

            // 使用 category 作为键名，保持与模板一致
            model.addAttribute("category", categoryList);

        } catch (Exception e) {
            log.error("处理菜单数据失败: ", e);
            model.addAttribute("category", new ArrayList<>());
        }
    }

    /**
     * 处理案例相关的所有请求
     */
    @GetMapping({"/case", "/case/{category}", "/case/{category}/{slug}"})
    public String handleCase(
        @PathVariable(required = false) String category,
        @PathVariable(required = false) String slug,
        Model model) {
        try {
            addCommonData(model);

            // 查询 application 父分类
            CmsCategoryBo parentBo = new CmsCategoryBo();
            parentBo.setPath("application");
            List<CmsCategoryVo> parentCategories = categoryService.queryList(parentBo);

            if (!parentCategories.isEmpty()) {
                CmsCategoryVo parentCategory = parentCategories.get(0);

                // 查询 application 子分类
                CmsCategoryBo queryBo = new CmsCategoryBo();
                queryBo.setParentId(parentCategory.getId());
                List<CmsCategoryVo> applicationCategories = categoryService.queryList(queryBo);
                model.addAttribute("applicationCategories", applicationCategories);

                if (category != null) {
                    // 查找当前选中的分类
                    CmsCategoryBo categoryBo = new CmsCategoryBo();
                    categoryBo.setPath(category);
                    List<CmsCategoryVo> currentCategories = categoryService.queryList(categoryBo);

                    if (!currentCategories.isEmpty()) {
                        CmsCategoryVo currentCategory = currentCategories.get(0);
                        model.addAttribute("currentCategory", currentCategory);

                        // 查询当前分类下的文章
                        CmsArticleBo articleBo = new CmsArticleBo();
                        articleBo.setCategoryId(currentCategory.getId());
                        List<CmsArticleVo> articles = articleService.queryList(articleBo);
                        model.addAttribute("articles", articles);

                        log.info("当前分类: {}, 文章数量: {}", currentCategory.getTitle(), articles.size());
                    }
                } else {
                    // 显示第一个分类的内容
                    if (!applicationCategories.isEmpty()) {
                        CmsCategoryVo firstCategory = applicationCategories.get(0);
                        model.addAttribute("currentCategory", firstCategory);

                        CmsArticleBo articleBo = new CmsArticleBo();
                        articleBo.setCategoryId(firstCategory.getId());
                        List<CmsArticleVo> articles = articleService.queryList(articleBo);
                        model.addAttribute("articles", articles);

                        log.info("默认显示第一个分类: {}, 文章数量: {}", firstCategory.getTitle(), articles.size());
                    }
                }
            }

            return "case";
        } catch (Exception e) {
            log.error("处理案例请求失败: {}", e.getMessage());
            return "error/404";
        }
    }
}
